package ch.kerbtier.webglue;

import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GlueServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response, getServletContext(), getServletConfig());
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response, getServletContext(), getServletConfig());
	}

	private void doRequest(HttpServletRequest request,
			HttpServletResponse response, ServletContext servletContext,
			ServletConfig servletConfig) {
		final GroovyScriptEngine engine = (GroovyScriptEngine) servletContext
				.getAttribute("glue_groovy_engine");
		final Binding binding = new Binding();

		
		boolean sessionIsNew = request.getSession(false) == null;
		
		
		binding.setVariable("request", request);
		binding.setVariable("session", request.getSession());
		binding.setVariable("newSession", sessionIsNew);
		binding.setVariable("response", response);
		binding.setVariable("context", servletContext);
		binding.setVariable("servletContext", servletContext);
		binding.setVariable("servletConfig", servletConfig);

		binding.setVariable("script", new Object() {
			public Object evaluate(String name) {
				try {
					return engine.run(name, binding);
				} catch (ResourceException e) {
					e.printStackTrace();
				} catch (ScriptException e) {
					e.printStackTrace();
				} catch (Throwable e) {
					e.printStackTrace();
				}
				return null;
			}
		});

		try {
			engine.run(servletConfig.getInitParameter("name") + ".groovy",
					binding);
		} catch (ResourceException e) {
			e.printStackTrace();
		} catch (ScriptException e) {
			e.printStackTrace();
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	@Override
	public void destroy() {
	}

	@Override
	public void init() throws ServletException {
	}
}
